<template>
  <!-- 异常品通知单表单弹窗 -->
  <div>
    <el-dialog
      v-model="visibleDialog"
      :title="props.title"
      width="1200px"
      draggable
      @close="closeDialog"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :inline="true"
        :rules="rules"
        label-width="160"
      >
        <h4 class="mb-[20px] mt-[0px]">基本数据</h4>
        <div>
          <el-row>
            <el-col :span="8">
              <el-form-item label="设备编码" prop="equipCode">
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.equipCode"
                  placeholder="请选择设备"
                  clearable
                  readonly
                  style="width: 100%"
                  @click="openSelectDialog"
                >
                  <template #append>
                    <el-button type="success" plain @click="openSelectDialog"
                      >选择</el-button
                    >
                  </template>
                </el-input>
                <span v-else>{{ formData.equipCode }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="产品" prop="productId">
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.productCode"
                  placeholder="请选择成品物料"
                  clearable
                  readonly
                  style="width: 100%"
                  @click="showWorkOrderSelect"
                >
                  <template #append>
                    <el-button type="success" plain @click="showWorkOrderSelect"
                      >选择</el-button
                    >
                  </template>
                </el-input>
                <span v-else>{{ formData.productCode }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="异常品通知单号" prop="noticeCode">
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.noticeCode"
                  placeholder="请输入异常品通知单号"
                  readonly
                  :disabled="true"
                  clearable
                />
                <span v-else>{{ formData.noticeCode }}</span>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="批次号" prop="batchNo">
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.batchNo"
                  placeholder="请输入批次号"
                  clearable
                />
                <span v-else>{{ formData.batchNo }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="异常数量" prop="abnormalNum">
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.abnormalNum"
                  placeholder="请输入异常数量"
                  clearable
                />
                <span v-else>{{ formData.abnormalNum }}</span>
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item label="比例%" prop="ratio">
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.ratio"
                  placeholder="请输入比例"
                  clearable
                />
                <span v-else>{{ formData.ratio }}</span>
              </el-form-item>
            </el-col>
          </el-row>
          <!-- <el-row>
            <el-col :span="8">
              <el-form-item
                v-if="props.isReadonly !== false"
                label="责任部门"
                prop="liableDepartmentName"
              >
                <span>{{ formData.liableDepartmentName }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="异常数量" prop="abnormalNum">
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.abnormalNum"
                  placeholder="请输入异常数量"
                  clearable
                />
                <span v-else>{{ formData.abnormalNum }}</span>
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item label="比例%" prop="ratio">
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.ratio"
                  placeholder="请输入比例"
                  clearable
                />
                <span v-else>{{ formData.ratio }}</span>
              </el-form-item>
            </el-col>
          </el-row> -->
        </div>
        <h4 class="mb-[20px] mt-[20px]">详细数据</h4>
        <el-button
          v-if="!props.isReadonly"
          type="success"
          plain
          @click="handleAdd"
          style="margin-bottom: 10px"
        >
          <i-ep-plus />
          新增</el-button
        >
        <div class="formTable2">
          <el-table
            :data="formData.details"
            style="width: 100%"
            :key="Math.random"
            border
          >
            <el-table-column
              type="index"
              label="序号"
              align="center"
              width="100"
            />
            <el-table-column label="问题描述" props="describes" min-width="150">
              <template #default="{ $index, row }">
                <el-form-item
                  :prop="'details.' + $index + '.describes'"
                  :rules="rules.sondescribes"
                  label-width="0"
                >
                  <el-input
                    v-if="!props.isReadonly"
                    v-model="row.describes"
                    placeholder="请输入问题描述"
                    clearable
                  />
                  <span v-else>{{ row.describes }}</span>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="问题要求" props="demand" min-width="150">
              <template #default="{ $index, row }">
                <el-form-item
                  :prop="'details.' + $index + '.demand'"
                  :rules="rules.sondemand"
                  label-width="0"
                >
                  <el-input
                    v-if="!props.isReadonly"
                    v-model="row.demand"
                    placeholder="请输入问题要求"
                    clearable
                  />
                  <span v-else>{{ row.demand }}</span>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="问题实际" props="actual" min-width="150">
              <template #default="{ $index, row }">
                <el-form-item
                  :prop="'details.' + $index + '.actual'"
                  :rules="rules.sonactual"
                  label-width="0"
                >
                  <el-input
                    v-if="!props.isReadonly"
                    v-model="row.actual"
                    placeholder="请输入问题实际"
                    clearable
                  />
                  <span v-else>{{ row.actual }}</span>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column
              fixed="right"
              align="center"
              label="操作"
              width="100"
              v-if="!props.isReadonly"
            >
              <template #default="scope">
                <el-button
                  :disabled="formData.details.length < 2"
                  type="danger"
                  link
                  @click.stop="handleDelete(scope.$index)"
                  ><i-ep-delete />
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <h4 class="mb-[20px] mt-[20px]">上传附件</h4>
        <CommonUploadFile
          :showText="false"
          :key="uploadKey"
          :files="formData.files || []"
          @update-files="updateFormFiles"
        />
        <div
          v-if="
            !props.isReadonly &&
            (formData.status === '' || props.judgment !== 1)
          "
        >
          <h4 class="mb-[20px] mt-[20px]">质量部门</h4>
          <el-row>
            <el-col :span="8" :offset="16">
              <el-form-item label="质量部门" prop="qualityDepartmentId">
                <el-tree-select
                  v-model="formData.qualityDepartmentId"
                  v-if="!props.isReadonly"
                  :data="organizationList"
                  filterable
                  :props="defaultProps"
                  :node-key="defaultProps.value"
                  :check-strictly="true"
                  :show-checkbox="true"
                  check-on-click-node
                  placement="top"
                  style="width: 100%"
                  clearable
                />
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button
            v-if="
              !props.isReadonly &&
              (formData.status === '' || props.judgment === 1)
            "
            type="primary"
            :loading="loading"
            @click="qualityJudgmentSubmit"
            >提交责任判定</el-button
          >
          <el-button
            v-if="!props.isReadonly"
            type="primary"
            :loading="loading"
            @click="handleSubmit"
            >确 定</el-button
          >
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <produce-product-select
      :visible="productDialogSelect.visible"
      @change-visible="changeProductVisible"
      :plantId="formData.plantId"
      :materialType="3"
      :backList="productBackList"
    />
    <SelectDeviceDialog-Eam
      v-model:visible="selectDialog.visible"
      :data="selectDialog.data"
      :isMultiple="false"
      @echo-info="changeVisible"
    />
  </div>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary";
import {
  validateDegree,
  validateNumber,
  validatePositiveInteger,
} from "@/utils/commonHooks"; // 引入
const dictionaryStore = useDictStoreHook();

defineOptions({
  name: "QMSPRODUCEROKNOTICEDOCADDORUPDATE",
  inheritAttrs: false,
});

const uploadKey = ref(Math.random());

const defaultProps = {
  children: "nodes",
  label: "organizationName",
  value: "id",
};
const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  judgment: {
    type: Number,
    default: () => {
      return 0;
    },
  },
});

/** 弹窗显示 **/
const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
    setTimeout(() => {
      formRef.value.clearValidate();
    }, 50);
    console.log(111);
    generateNoticeCode();
  }
);

/** formData定义表单数据 */
const formRef = ref(ElForm);
let formData = reactive({
  id: "",
  version: "",
  status: "",
  workStatus: "",
  noticeCode: "",
  noticeDate: "",
  noticeDepartmentCode: "",
  noticeDepartmentName: "",
  noticeDepartmentId: "",
  noticeUserId: "",
  noticeUserName: "",
  liableDepartmentId: "",
  liableDepartmentName: "",
  qualityDepartmentId: "",
  qualityDepartmentName: "",
  equipId: "",
  equipCode: "",
  equipName: "",
  productId: "",
  productCode: "",
  productName: "",
  materialNo: "",
  batchNo: "",
  abnormalNum: "",
  judgeUserName: "",
  judgeUserId: "",
  judgeTime: "",
  ratio: "",
  remarks: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  enabled: "",
  deleted: "",
  files: [],
  details: [
    {
      id: "",
      version: "",
      noticeDocId: "",
      describes: "",
      demand: "",
      actual: "",
      remarks: "",
      createTime: "",
      createdUserId: "",
      createdUserName: "",
      lastUpdateTime: "",
      lastUpdatedUserId: "",
      lastUpdatedUserName: "",
      enabled: "",
      deleted: "",
    },
  ],
});

const validatePositiveInteger = (rule, value, callback: (a?: any) => {}) => {
  if (/^[+]{0,1}(\d+)$/.test(value)) {
    //验证正整数和0的正则
    return true;
  } else {
    callback(new Error("请输入数字"));
  }
};

/** rules规则 */
const rules = reactive({
  status: [],
  workStatus: [],
  noticeCode: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  noticeDate: [],
  noticeDepartmentCode: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  noticeDepartmentName: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  noticeUserName: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  liableDepartmentName: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  equipCode: [
    { required: true, message: "请选择设备", trigger: "blur" },
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  equipName: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  productId: [
    { required: true, message: "请选择产品", trigger: "blur" },
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  productCode: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  productName: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  materialNo: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  batchNo: [
    { required: true, message: "请输入批次号", trigger: "blur" },
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  qualityDepartmentId: [
    { required: true, message: "请选择质量部门", trigger: "blur" },
  ],
  abnormalNum: [
    { required: true, message: "请输入异常数量", trigger: "blur" },
    {
      validator: validatePositiveInteger,
      trigger: "blur",
    },
  ],
  judgeUserName: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  judgeTime: [],
  ratio: [
    { required: true, message: "请输入比例", trigger: "blur" },
    {
      validator: validateNumber,
      trigger: "blur",
    },
  ],
  remarks: [
    { min: 1, max: 255, message: "长度在 1 到 255 个字符", trigger: "blur" },
  ],
  createTime: [],
  createdUserName: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  lastUpdateTime: [],
  lastUpdatedUserName: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  enabled: [],
  sondescribes: [
    { required: true, message: "请填写问题描述", trigger: "blur" },
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  sondemand: [
    { required: true, message: "请填写问题要求", trigger: "blur" },
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  sonactual: [
    { required: true, message: "请填写问题实际", trigger: "blur" },
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
});

const isValidated = ref(false);
/** 删除行 */
const handleDelete = (index: any) => {
  formData.details.splice(index, 1);
  isValidated.value && formRef.value.validate(() => {});
};

const details = {
  id: "",
  version: "",
  noticeDocId: "",
  describes: "",
  demand: "",
  actual: "",
  remarks: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  enabled: "",
  deleted: "",
};

/** 添加行 */
const handleAdd = () => {
  let sondata = JSON.parse(JSON.stringify(details));
  formData.details.push(sondata);
};
//选择成品弹窗
const productDialogSelect = ref({
  visible: false,
});
const changeProductVisible = (val: boolean, data: any) => {
  productDialogSelect.value.visible = val;
  if (data) {
    formData.productId = data.id;
    formData.productName = data.materialName;
    formData.productCode = data.materialCode;
  }
};
// 回显的数据
const productBackList = ref([]);
const showWorkOrderSelect = () => {
  productDialogSelect.value.visible = true;
};
/** 编辑时赋值 */
watch(
  () => props.data,
  (newVal: any) => {
    formData.id = "";
    if (newVal?.id) {
      Object.assign(formData, props.data);
      if (formData.id) {
        getdetails();
        getFiles();
      }
    }
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  uploadKey.value = Math.random();
  resetForm();
}
function generateNoticeCode() {
  const currentDate = new Date();
  const year = String(currentDate.getFullYear()).slice(-2);
  const month = String(currentDate.getMonth() + 1).padStart(2, "0");
  const day = String(currentDate.getDate()).padStart(2, "0");
  const hour = String(currentDate.getHours()).padStart(2, "0");
  const minute = String(currentDate.getMinutes()).padStart(2, "0");
  const second = String(currentDate.getSeconds()).padStart(2, "0");
  const randomNum = String(Math.floor(1000 + Math.random() * 9000)).slice(-3);
  const noticeCode = `YCTZ${month}${day}${hour}${minute}${second}${randomNum}`;
  formData.noticeCode = noticeCode;
}
/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.details = [JSON.parse(JSON.stringify(details))];
  formData.files = [];
  formData.id = "";
  formData.version = "";
  formData.status = "";
  formData.workStatus = "";
  formData.noticeCode = "";
  formData.noticeDate = "";
  formData.noticeDepartmentCode = "";
  formData.noticeDepartmentName = "";
  formData.noticeDepartmentId = "";
  formData.noticeUserId = "";
  formData.noticeUserName = "";
  formData.liableDepartmentId = "";
  formData.liableDepartmentName = "";
  formData.qualityDepartmentId = "";
  formData.qualityDepartmentName = "";
  formData.equipId = "";
  formData.equipCode = "";
  formData.equipName = "";
  formData.productId = "";
  formData.productCode = "";
  formData.productName = "";
  formData.materialNo = "";
  formData.batchNo = "";
  formData.abnormalNum = "";
  formData.judgeUserName = "";
  formData.judgeUserId = "";
  formData.judgeTime = "";
  formData.ratio = "";
  formData.remarks = "";
  formData.createTime = "";
  formData.createdUserId = "";
  formData.createdUserName = "";
  formData.lastUpdateTime = "";
  formData.lastUpdatedUserId = "";
  formData.lastUpdatedUserName = "";
  formData.enabled = "";
  formData.deleted = "";
}

const loading = ref(false);

/** 异常品通知单保存提交 */
function handleSubmit() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      loading.value = true;
      const text = formData.id ? "编辑" : "新增";
      console.log("formData", toRaw(formData));
      await request({
        url: "/qms/roknoticedoc/save",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      emit("reset-table", formData.id);
      isValidated.value = false;
    } else {
      isValidated.value = true;
    }
  });
}

async function getdetails() {
  let sondetails = await request({
    url: "/qms/roknoticedoc/getDetails",
    method: "post",
    data: formData,
  }).finally(() => {
    loading.value = false;
  });
  formData.details = sondetails.data;
}
async function getFiles() {
  await request({
    url: "/qms/roknoticeviewdetail/getOneByType",
    method: "post",
    data: { noticeId: formData.id, viewType: 0 },
  })
    .then(async ({ data }) => {
      let sondetails = await request({
        url: "/qms/rokmonitorworkfile/getFiles",
        method: "post",
        data: { monitorWorkId: data.id, monitorWorkFileType: 0 },
      }).finally(() => {
        loading.value = false;
      });
      formData.files = sondetails.data;
      uploadKey.value = Math.random();
    })
    .finally(() => {
      loading.value = false;
    });
}

//设备显隐
const selectDialog = reactive<DialogOption>({
  visible: false,
  data: [],
});
//  点击设备
function openSelectDialog() {
  selectDialog.visible = true;
  selectDialog.data = formData.equipId
    ? [
        {
          id: formData.equipId,
          assetName: formData.equipName,
          assetCode: formData.equipCode,
        },
      ]
    : [];
}
// 设备选择确认后的回调函数
const changeVisible = (options: any) => {
  if (options && options.length) {
    const data = options[0];
    formData.equipId = data.id;
    formData.equipCode = data.assetCode;
    formData.equipName = data.assetName;
  } else {
    formData.equipId = "";
    formData.equipCode = "";
    formData.equipName = "";
  }
};
// 图片处理
function updateFormFiles(val: []) {
  formData.files = val;
}

const qualityJudgmentSubmit = () => {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      loading.value = true;
      const text = "提交";
      await request({
        url: "/qms/roknoticedoc/judgmentSubmit",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      emit("reset-table", formData.id);
      isValidated.value = false;
    } else {
      isValidated.value = true;
    }
  });
};
const organizationList = ref([]);

const getOrganizationList = async () => {
  const { data } = await request({
    url: "/system/sysOrganization/getUsableTree",
    method: "post",
    data: {},
  });
  organizationList.value = data;
};
onMounted(() => {
  getOrganizationList();
});
// 定义一个递归函数来扁平化树形结构
function flattenTree(tree) {
  let result = [];

  function traverse(node) {
    result.push(node);
    if (node.nodes && node.nodes.length > 0) {
      node.nodes.forEach((child) => traverse(child));
    }
  }

  tree.forEach((node) => traverse(node));
  return result;
}
watch(
  () => formData.qualityDepartmentId,
  (departmentId) => {
    const find = flattenTree(organizationList.value).find(
      (item) => item.id === departmentId
    );
    formData.qualityDepartmentName = find?.organizationName || "";
  }
);
</script>

<style lang="scss" scoped>
h4 {
  font-weight: 400;
  color: #000;
  padding-left: 10px;
  font-size: 14px;
  line-height: 14px;
}

// .formTable {
//   :deep(.el-form-item) {
//     margin-right: 0 !important;
//   }
// }

:deep(.el-dialog .el-dialog__body) {
  overflow-y: auto;
  height: 65vh;
}

:deep.el-input.el-input--default.el-input--suffix {
  // 固定宽度
  width: 190px !important;
}

.formTable2 {
  :deep(.el-form-item) {
    margin: 0 0 13px 0 !important;
    width: 100%;
  }
}
:deep(.el-dialog .formTable2 .el-table .el-form-item) {
  padding: 11px 0 0 0 !important;
}
:deep(.el-dialog .formTable2 .el-table .el-form-item__error) {
  font-size: 11px !important;
}

:deep(.el-dialog .formTable2 .el-table) {
  .el-table__body td.el-table__cell {
    // padding: 5px !important;
    padding: 0 !important;
  }
}
</style>
